package com.zby.business.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.zby.business.R;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;
import com.zby.business.util.Util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by BY on 2016/1/20.
 */
public class Order extends Activity implements View.OnClickListener {
    private TextView allTextView, toBeshippedTextView, toBeReceivedTextView, toBeEvaluateTextView;
    private ViewPager orderViewPager;
    private View navigatView;
    private Display display;
    private int screenWidth;
    private LinearLayout.LayoutParams layoutParams;
    private ArrayList<View> views;
    private ArrayList<TextView> textViews;
    private LayoutInflater inflater;
    private App app;
    private ArrayList commodityPrice, commodityName, commodityPicture, commodityIntroduce, commodityDetailId, commoditySale;
    private ArrayList time, orderId, number;
    private LruCache cache;
    private ImageLoader imageLoader;
    private OrderAdapter adapter0, adapter1, adapter2, adapter3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order);
        init();
        Bundle bundle = getIntent().getExtras();
        orderViewPager.setCurrentItem(bundle.getInt("position"));

    }

    private void init() {
        inflater = LayoutInflater.from(getApplicationContext());
        imageLoader = ImageLoader.getInstance();
        ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(getApplicationContext());
        imageLoader.init(config);
        cache = new LruCache((int) (Runtime.getRuntime().maxMemory() / 20));
//        commodityName = new ArrayList();
//        commodityPicture = new ArrayList();
//        commodityPrice = new ArrayList();
//        commodityIntroduce = new ArrayList();
//        commodityDetailId = new ArrayList();
//        commoditySale = new ArrayList();
//        orderId = new ArrayList();
//        time = new ArrayList();
//        number = new ArrayList();
        app = (App) getApplication();
        views = new ArrayList<View>();
        textViews = new ArrayList<TextView>();
        inflater = LayoutInflater.from(getApplicationContext());
        orderViewPager = (ViewPager) findViewById(R.id.orderViewPager);
        navigatView = findViewById(R.id.naigatView);
        display = getWindowManager().getDefaultDisplay();
        screenWidth = display.getWidth();
        allTextView = (TextView) findViewById(R.id.myOrderTextView);
//        toBePaidTextView = (TextView) findViewById(R.id.toBePaidTextView);
        toBeshippedTextView = (TextView) findViewById(R.id.toBeShippedTextView);
        toBeReceivedTextView = (TextView) findViewById(R.id.toBeReceivedTextView);
        toBeEvaluateTextView = (TextView) findViewById(R.id.toBeEvaluateTextView);
        allTextView.setOnClickListener(this);
//        toBePaidTextView.setOnClickListener(this);
        toBeshippedTextView.setOnClickListener(this);
        toBeReceivedTextView.setOnClickListener(this);
        toBeEvaluateTextView.setOnClickListener(this);
        textViews.add(allTextView);
//        textViews.add(toBePaidTextView);
        textViews.add(toBeshippedTextView);
        textViews.add(toBeReceivedTextView);
        textViews.add(toBeEvaluateTextView);
        layoutParams = (LinearLayout.LayoutParams) navigatView.getLayoutParams();
        addMyOrder();
//        for (int i = 0; i < 3; i++) {
//        View view = inflater.inflate(R.layout.pull_to_refresh_view, null);
//        ScrollView scrollView = (ScrollView) view.findViewById(R.id.scrollView);
//        System.out.println(scrollView.getPaddingTop());
//        views.add(view);
//        }

        OrderViewPagerAdapter pagerAdapter = new OrderViewPagerAdapter();
        orderViewPager.setAdapter(pagerAdapter);
        orderViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                layoutParams.setMargins((int) (screenWidth / 4 * (position + positionOffset)), 0, 0, 0);
                navigatView.setLayoutParams(layoutParams);
                textViews.get(position).setTextColor(Color.parseColor(changeColor(positionOffset)));
                if (!(position + 1 == textViews.size())) {
                    textViews.get(position + 1).setTextColor(Color.parseColor(changeColor(1 - positionOffset)));
                }
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == 0) {
                    for (TextView textView : textViews) {
                        textView.setTextColor(Color.WHITE);
                    }
                    textViews.get(orderViewPager.getCurrentItem()).setTextColor(Color.RED);
                }
            }
        });
        layoutParams.width = screenWidth / 4;
    }

    private void addMyOrder() {
        for (int j = -1; j < 3; j++) {
            ArrayList commodityPrice, commodityName, commodityPicture, commodityIntroduce, commodityDetailId, commoditySale;
            ArrayList time, orderId, number;
            commodityName = new ArrayList();
            commodityPicture = new ArrayList();
            commodityPrice = new ArrayList();
            commodityIntroduce = new ArrayList();
            commodityDetailId = new ArrayList();
            commoditySale = new ArrayList();
            orderId = new ArrayList();
            time = new ArrayList();
            number = new ArrayList();
            View view = inflater.inflate(R.layout.myorder, null);
            ListView orderListView = (ListView) view.findViewById(R.id.orderListView);
            String url = "getOrder?userId=" + app.getUserId() + "&status=" + j;
            MyAsyncTask asyncTask = new MyAsyncTask();
            try {
                String s = asyncTask.execute(url).get();
                System.out.println(s);
                JSONObject json = new JSONObject(s);
                JSONArray orders = json.getJSONArray("order");
                JSONArray details = json.getJSONArray("detail");
                for (int i = 0; i < orders.length(); i++) {
                    JSONObject detail = (JSONObject) details.get(i);
                    JSONObject order = (JSONObject) orders.get(i);
                    commodityDetailId.add(detail.get("commodityDetailId"));
                    commodityName.add(detail.get("commodityBrand"));
                    commodityPrice.add(detail.get("commodityPrice"));
                    commodityPicture.add(detail.get("commodityPicture"));
                    commodityIntroduce.add(detail.get("commodityIntroduce"));
                    commoditySale.add(detail.get("commoditySale"));
                    time.add(order.get("time"));
                    number.add(order.get("number"));
                    orderId.add(order.get("orderid"));
                }
                if (j == -1) {
                    adapter0 = new OrderAdapter(commodityDetailId, commodityName, commodityPicture, commodityPrice, commodityIntroduce, commoditySale, time, number, orderId, j);
                    orderListView.setAdapter(adapter0);
                } else if (j == 0) {
                    adapter1 = new OrderAdapter(commodityDetailId, commodityName, commodityPicture, commodityPrice, commodityIntroduce, commoditySale, time, number, orderId, j);
                    orderListView.setAdapter(adapter1);
                } else if (j == 1) {
                    adapter2 = new OrderAdapter(commodityDetailId, commodityName, commodityPicture, commodityPrice, commodityIntroduce, commoditySale, time, number, orderId, j);
                    orderListView.setAdapter(adapter2);
                } else if (j == 2) {
                    adapter3 = new OrderAdapter(commodityDetailId, commodityName, commodityPicture, commodityPrice, commodityIntroduce, commoditySale, time, number, orderId, j);
                    orderListView.setAdapter(adapter3);
                }
                if (commodityDetailId.size() == 0) {
                    views.add(inflater.inflate(R.layout.textview, null));
                } else {
                    views.add(view);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String changeColor(float positionOffset) {
        int l = Integer.parseInt("ffff", 16);
        int color = (int) (l * positionOffset);
        String index = Integer.toHexString(color);
        if (index.length() == 1) {
            index = "000" + index;
        } else if (index.length() == 2) {
            index = "00" + index;
        } else if (index.length() == 3) {
            index = "0" + index;
        }
        return "#ff" + index;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.myOrderTextView:
                orderViewPager.setCurrentItem(0);
                break;
//            case R.id.toBePaidTextView:
//                orderViewPager.setCurrentItem(1);
//                break;
            case R.id.toBeShippedTextView:
                orderViewPager.setCurrentItem(1);
                break;
            case R.id.toBeReceivedTextView:
                orderViewPager.setCurrentItem(2);
                break;
            case R.id.toBeEvaluateTextView:
                orderViewPager.setCurrentItem(3);
                break;
        }
    }

    private void changeStatus(String orderId, int status) {
        MyAsyncTask asyncTask = new MyAsyncTask();
        try {
            String s = asyncTask.execute("changeStatus?orderId=" + orderId + "&status=" + status + "&userId=" + app.getUserId()).get();
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class OrderViewPagerAdapter extends PagerAdapter {


        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    class OrderAdapter extends BaseAdapter {
        private ArrayList commodityPrice, commodityName, commodityPicture, commodityIntroduce, commodityDetailId, commoditySale;
        private ArrayList time, orderId, number;
        private int index;
        private AlertDialog.Builder alert;

        public OrderAdapter(ArrayList commodityDetailId, ArrayList commodityName, ArrayList commodityPicture, ArrayList commodityPrice, ArrayList commoditySale, ArrayList commodityIntroduce, ArrayList time, ArrayList number, ArrayList orderId, int index) {
            this.commodityDetailId = commodityDetailId;
            this.commodityIntroduce = commodityIntroduce;
            this.commodityName = commodityName;
            this.commodityPicture = commodityPicture;
            this.commodityPrice = commodityPrice;
            this.commoditySale = commoditySale;
            this.time = time;
            this.number = number;
            this.orderId = orderId;
            this.index = index;
            alert = new AlertDialog.Builder(Order.this, AlertDialog.THEME_HOLO_LIGHT);
            alert.setNegativeButton("取消", null);
        }

        @Override
        public int getCount() {
            return orderId.size();
        }

        @Override
        public Object getItem(int position) {
            return orderId.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Button orderButton;
            if (index == -1) {
                convertView = inflater.inflate(R.layout.order_list_view, null);
            } else if (index == 0) {
                convertView = inflater.inflate(R.layout.order_list_view1, null);
                orderButton = (Button) convertView.findViewById(R.id.orderButton);
                orderButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alert.setMessage("取消订单");
                        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changeStatus(orderId.get(position) + "", 1);
                                app.setAccount(app.getAccount() + Integer.parseInt(number.get(position) + "") * Float.parseFloat(commodityPrice.get(position) + ""));
                                commoditySale.remove(position);
                                commodityPrice.remove(position);
                                commodityName.remove(position);
                                commodityPicture.remove(position);
                                commodityIntroduce.remove(position);
                                commodityDetailId.remove(position);
                                time.remove(position);
                                orderId.remove(position);
                                number.remove(position);
                                if (index == -1) {
                                    adapter0.notifyDataSetChanged();
                                } else if (index == 0) {
                                    adapter1.notifyDataSetChanged();
                                } else if (index == 1) {
                                    adapter2.notifyDataSetChanged();
                                }
                            }
                        });
                        alert.show();
                    }
                });
            } else if (index == 1) {
                convertView = inflater.inflate(R.layout.order_list_view2, null);
                orderButton = (Button) convertView.findViewById(R.id.orderButton);
                orderButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alert.setMessage("签收");
                        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changeStatus(orderId.get(position) + "", 2);
                                commoditySale.remove(position);
                                commodityPrice.remove(position);
                                commodityName.remove(position);
                                commodityPicture.remove(position);
                                commodityIntroduce.remove(position);
                                commodityDetailId.remove(position);
                                time.remove(position);
                                orderId.remove(position);
                                number.remove(position);
                                if (index == -1) {
                                    adapter0.notifyDataSetChanged();
                                } else if (index == 0) {
                                    adapter1.notifyDataSetChanged();
                                } else if (index == 1) {
                                    adapter2.notifyDataSetChanged();
                                }
                            }
                        });
                        alert.show();
                    }
                });
            } else if (index == 2) {
                convertView = inflater.inflate(R.layout.order_list_view, null);
            }

            final String[] urls = commodityPicture.get(position).toString().split("\\;");
            final ImageView orderImage = (ImageView) convertView.findViewById(R.id.orderListViewImage);
            TextView orderIntroduce = (TextView) convertView.findViewById(R.id.orderIntroduceTextView);
            TextView orderprice = (TextView) convertView.findViewById(R.id.orderPriceText);
            TextView orderNumber = (TextView) convertView.findViewById(R.id.orderNumberText);
            TextView orderCount = (TextView) convertView.findViewById(R.id.orderCountText);
            TextView orderTime = (TextView) convertView.findViewById(R.id.orderTimeText);
            orderIntroduce.setText(commodityName.get(position) + "");
            orderprice.setText(commodityPrice.get(position) + "");
            orderNumber.setText("*" + number.get(position));
            orderCount.setText("共" + number.get(position) + "件商品，合计:￥" + Integer.parseInt(number.get(position) + "") * Float.parseFloat(commodityPrice.get(position) + ""));
            orderTime.setText(time.get(position) + "");
            Bitmap bitmap = (Bitmap) cache.get(urls[0]);
            if (bitmap != null) {
                orderImage.setImageBitmap(bitmap);
            } else {
                imageLoader.displayImage(Util.BASE_URL + urls[0], orderImage);
                imageLoader.loadImage(Util.BASE_URL + urls[0], new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        cache.put(urls[0], bitmap);
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {

                    }
                });
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getApplicationContext(), Detail.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("introduce", commodityIntroduce.get(position) + "");
                    bundle.putString("price", commodityPrice.get(position) + "");
                    bundle.putString("sale", commoditySale.get(position) + "");
                    bundle.putString("commodityId", commodityDetailId.get(position) + "");
                    bundle.putString("url", commodityPicture.get(position) + "");
                    intent.putExtra("bundle", bundle);
                    startActivity(intent);
                }
            });
            return convertView;
        }
    }
}
